package com.wt.springsamples.config;

import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class HttpClientTemplate {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientTemplate.class);
    private static final String UTF_8 = StandardCharsets.UTF_8.name();
    public static final String JSON_CONTENT_TYPE = "application/json";
    @Autowired
    private CloseableHttpClient httpClient;

    public String doPut(String url, String entityStr) {
        HttpPut httpPut = new HttpPut(url);
        StringEntity strEntity = new StringEntity(entityStr, UTF_8);
        httpPut.setEntity(strEntity);
        return sendHttpPut(httpPut, null);
    }

    public String doPut(String url, String entityStr, Map<String,String> headerMap) {
        HttpPut httpPut = new HttpPut(url);
        StringEntity strEntity = new StringEntity(entityStr, UTF_8);
        strEntity.setContentType(JSON_CONTENT_TYPE);
        httpPut.setEntity(strEntity);
        return sendHttpPut(httpPut, headerMap);
    }

    public String doGet(String url) {
        HttpGet httpGet = new HttpGet(url);
        return sendHttpGet(httpGet, null);
    }

    public String doGet(String url, Map<String, String> params, Map<String, String> headerMap) {
        HttpGet httpGet = new HttpGet(appendRequestParams(url, params));
        return sendHttpGet(httpGet, headerMap);
    }

    public String doGet(String url, Map<String, String> headerMap) {
        HttpGet httpGet = new HttpGet(url);
        return sendHttpGet(httpGet, headerMap);
    }

    private static String appendRequestParams(String url, Map<String, String> params) {
        if (!CollectionUtils.isEmpty(params)) {
            List<NameValuePair> formParams = new ArrayList<>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            try {
                return url + (url.contains("?") ? "&" : "?")
                        + EntityUtils.toString(new UrlEncodedFormEntity(formParams, "UTF-8"));
            } catch (Exception e) {
                LOGGER.error("拼接Get请求Url[{}]异常", url, e);
            }
        }
        return url;
    }

    private String sendHttpPost(HttpPost httpPost, Map<String,String> headerMap) {
        CloseableHttpResponse response = null;
        String responseContent = null;
        try {
            setHeaders(headerMap, httpPost);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, UTF_8);
        } catch (Exception e) {
            LOGGER.error("send http post request fail !", e);
        } finally {
            closeResponse(response);
        }
        return responseContent;
    }

    public String doPost(String url, String entityStr) {
        HttpPost httpPost = new HttpPost(url);
        StringEntity strEntity = new StringEntity(entityStr, UTF_8);
        httpPost.setEntity(strEntity);
        return sendHttpPost(httpPost, null);
    }

    public String doPostJson(String url, String entityStr) {
        HttpPost httpPost = new HttpPost(url);
        StringEntity strEntity = new StringEntity(entityStr, UTF_8);
        strEntity.setContentType(JSON_CONTENT_TYPE);
        httpPost.setEntity(strEntity);
        return sendHttpPost(httpPost,null);
    }

    public String doPostJson(String url, String entityStr, Map<String, String> headerMap) {
        HttpPost httpPost = new HttpPost(url);
        StringEntity strEntity = new StringEntity(entityStr, UTF_8);
        strEntity.setContentType(JSON_CONTENT_TYPE);
        httpPost.setEntity(strEntity);
        return sendHttpPost(httpPost, headerMap);
    }

    public void closeResponse(CloseableHttpResponse response) {
        if (response == null) {
            return;
        }
        try {
            EntityUtils.consume(response.getEntity());
        } catch (IOException e) {
            LOGGER.error("close response content stream fail !", e);
        }
        try {
            response.close();
        } catch (IOException e) {
            LOGGER.error("close response fail !", e);
        }
    }

    private void setHeaders(Map<String, String> headerMap, HttpRequest httpRequest) {
        if (headerMap == null || headerMap.isEmpty()) return;
        for (Map.Entry<String, String> headerEntry : headerMap.entrySet()) {
            httpRequest.addHeader(headerEntry.getKey(), headerEntry.getValue());
        }
    }

    private void setCookies(Map<String, String> cookieMap, HttpContext httpContext) {
        if (cookieMap == null || cookieMap.isEmpty()) {
            return;
        }
        BasicCookieStore cookieStore = new BasicCookieStore();
        for (Map.Entry<String, String> cookieEntry : cookieMap.entrySet()) {
            BasicClientCookie cookie = new BasicClientCookie(cookieEntry.getKey(), cookieEntry.getValue());
            cookie.setDomain(".migu.cn");
            cookie.setPath("/");
            cookieStore.addCookie(cookie);
            httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
        }
    }


    private String sendHttpGet(HttpGet httpGet, Map<String, String> headerMap) {
        CloseableHttpResponse response = null;
        String responseContent = null;
        try {
            setHeaders(headerMap, httpGet);
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, UTF_8);
        } catch (Exception e) {
            LOGGER.error("send http get request fail !", e);
        } finally {
            closeResponse(response);
        }
        return responseContent;
    }

    private String sendHttpPost(HttpPost httpPost, Map<String, String> headerMap, Map<String, String> cookieMap) {
        HttpContext httpContext = new BasicHttpContext();
        CloseableHttpResponse response = null;
        String responseContent = null;
        try {
            setHeaders(headerMap, httpPost);
            setCookies(cookieMap, httpContext);
            response = httpClient.execute(httpPost, httpContext);
            HttpEntity entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, UTF_8);
        } catch (Exception e) {
            LOGGER.error("send http post request fail !", e);
        } finally {
            closeResponse(response);
        }

        return responseContent;
    }


    private String sendHttpPut(HttpPut httpPut, Map<String,String> headerMap){
        CloseableHttpResponse response =null;
        String responseContent = null;
        try {
            setHeaders(headerMap, httpPut);
            response = httpClient.execute(httpPut);
            HttpEntity entity =response.getEntity();
            responseContent =EntityUtils.toString(entity,UTF_8);
        }catch (Exception e){
            LOGGER.error("send http post request fail !",e);
        } finally{
            closeResponse(response);
        }
        return responseContent;
    }
}